﻿Imports Microsoft.Office.Tools.Ribbon
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Net
Imports System.IO
Imports System.Diagnostics

Public Class RibbonForecast

    Private Sub ButtonWorkflow_Click(ByVal sender As System.Object, ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles ButtonWorkflow.Click
        If Globals.ThisWorkbook.FullNameURLEncoded.Contains("http:") Then
            Using workflowWebSvc As WorkFlowSoapProxy.Workflow = New WorkFlowSoapProxy.Workflow()
                workflowWebSvc.Credentials = CType(CredentialCache.DefaultCredentials, NetworkCredential)
                Try
                    ' Get the workflow information
                    Dim itemWorkflowData = workflowWebSvc.GetWorkflowDataForItem(Globals.ThisWorkbook.FullNameURLEncoded)
                    ' And load it into an XmlDocument for searching
                    Dim workflowInfo = New XmlDocument()
                    ' The data is fragments so we have to surround it with an XML tag
                    workflowInfo.LoadXml("<WorkflowInformation>" + itemWorkflowData.InnerXml + "</WorkflowInformation>")
                    ' Next create an XPath statement to retrieve the data related to our workflow.
                    Dim nsMgr As System.Xml.XmlNamespaceManager = New XmlNamespaceManager(New NameTable())
                    nsMgr.AddNamespace("spWf", "http://schemas.microsoft.com/sharepoint/soap/workflow/")
                    ' Get the SalesForecastApprovalWorkflow
                    Dim documentApprovalWorkflowTemplate = _
                        workflowInfo.SelectSingleNode("//spWf:WorkflowTemplates/spWf:WorkflowTemplate[@Name='SalesForecastApprovalWorkflow']", nsMgr)
                    Dim documentApprovalWorkflowTemplateIdSet = documentApprovalWorkflowTemplate.SelectSingleNode("spWf:WorkflowTemplateIdSet", nsMgr)
                    Dim documentApprovalWorkflowTemplateId = documentApprovalWorkflowTemplateIdSet.Attributes("TemplateId").Value
                    Dim runningWorkflow As System.Xml.XmlNode = workflowInfo.SelectSingleNode("//spWf:ActiveWorkflowsData/spWf:Workflows/spWf:Workflow[@TemplateId='" + documentApprovalWorkflowTemplateId + "' and @Status1=2]", nsMgr)
                    If runningWorkflow IsNot Nothing Then
                        MessageBox.Show("The Workflow is already running for this SalesForecast.")
                    Else
                        ' Populate the initialization data for the workflow using the comments
                        ' from Sheet1.
                        Dim workflowData = New WorkflowInstantiationData()
                        Dim sysArray = CType(Globals.Sheet1.NamedRangeForecastComments.get_Value, System.Array)
                        If sysArray(1, 1) Is Nothing OrElse String.IsNullOrEmpty(sysArray(1, 1).ToString) Then
                            workflowData.comments = String.Empty
                        Else
                            workflowData.comments = sysArray(1, 1).ToString()
                        End If
                        Dim serializer As XmlSerializer = New System.Xml.Serialization.XmlSerializer(GetType(WorkflowInstantiationData))

                        Dim workflowParametersDocument = New XmlDocument()
                        Using stream As MemoryStream = New MemoryStream()
                            serializer.Serialize(stream, workflowData)
                            stream.Position = 0
                            workflowParametersDocument.Load(stream)
                        End Using
                        ' Start the workflow 
                        Dim startInfo = workflowWebSvc.StartWorkflow( _
                            Globals.ThisWorkbook.FullNameURLEncoded, _
                            New Guid(documentApprovalWorkflowTemplateId), _
                            workflowParametersDocument.DocumentElement)
                    End If
                Catch ex As Exception
                    MessageBox.Show(ex.Message)
                End Try
            End Using
        Else
            MessageBox.Show("The Workbook needs to be saved to the Sales Forecast library before starting the workflow.")
        End If
    End Sub

    Public Property IsTaskPaneVisible() As Boolean
        Get
            Return ToggleButtonTaskPane.Checked
        End Get
        Set(ByVal value As Boolean)
            ToggleButtonTaskPane.Checked = value
            If value Then
                ToggleButtonTaskPane.Label = "Hide Task Pane"
                ToggleButtonTaskPane.Image = Global.SalesForecastWorkbook.My.Resources.Resources.EditInformationHS
            Else
                ToggleButtonTaskPane.Label = "Show Task Pane"
                ToggleButtonTaskPane.Image = Global.SalesForecastWorkbook.My.Resources.Resources.ArrangeSideBySideHS
            End If
        End Set
    End Property


    Private Sub ToggleButton1_Click(ByVal sender As System.Object, ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles ToggleButtonTaskPane.Click
        Globals.ThisWorkbook.TaskPaneVisible = ToggleButtonTaskPane.Checked
    End Sub

    Private Sub DropDown1_SelectionChanged(ByVal sender As System.Object, ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles DropDown1.SelectionChanged
        ' Code can be added here which will call a method on the Actions pane and reset the forecast values
        ' based on a new data baseline.  This activity has been left to those working to better understand this
        ' sample code.
    End Sub


    Private Sub ButtonMonthlySalesGraph_Click(ByVal sender As System.Object, ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles ButtonMonthlySalesGraph.Click
        ' Lets create a new Graph on the spreadsheet...

        Dim chart As Excel.Chart = CType(Globals.ThisWorkbook.Charts.Add(), Microsoft.Office.Interop.Excel.Chart)
        chart.ChartType = Excel.XlChartType.xl3DColumnClustered
        chart.DisplayBlanksAs = Excel.XlDisplayBlanksAs.xlNotPlotted
        chart.SetSourceData(Globals.Sheet1.ListSales.Range)
        chart.ChartStyle = Globals.Sheet1.Chart_1.ChartStyle
        chart.Location(Excel.XlChartLocation.xlLocationAsObject, Globals.Sheet1.Name)
    End Sub

    Private Sub ButtonMonthlyForecastGraph_Click(ByVal sender As System.Object, ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles ButtonMonthlyForecastGraph.Click
        ' Lets create a new Graph on it's own sheet...

        Dim chart As Excel.Chart = CType(Globals.ThisWorkbook.Charts.Add(), Microsoft.Office.Interop.Excel.Chart)
        chart.ChartType = Excel.XlChartType.xl3DColumnClustered
        chart.DisplayBlanksAs = Excel.XlDisplayBlanksAs.xlNotPlotted
        chart.SetSourceData(Globals.Sheet1.ListForecast.Range)
        'In theory it is possible to ship a chart template which would 
        ' then be applied to the chart for fancier graphics and layout.
        ' For this demonstration the fancier elements have been left within the sheet
        ' Copying the style from these spreadsheets does not apply all of the graphics.
        'chart.ApplyChartTemplate()
        chart.ChartStyle = Globals.Sheet1.Chart_2.ChartStyle
        chart.Location(Excel.XlChartLocation.xlLocationAsNewSheet, "Forecast Chart")

    End Sub

    Private Sub ButtonReport_Click(ByVal sender As System.Object, ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles ButtonReport.Click
        '    Dim workbookurl As String = Globals.ThisWorkbook.FullName
        If Globals.ThisWorkbook.FullNameURLEncoded.Contains("http:") Then
            '    workbookurl = "http://moss.litwareinc.com/Docs/Sales%20Forecasts/workbook1.xlsx"
            'End If
            'Generate and load the document into SharePoint 
            Dim service As SalesForecastDocService.Service = _
               New SalesForecastWorkbook.SalesForecastDocService.Service()
            Dim documentUrl = String.Empty
            Try
                service.Credentials = CredentialCache.DefaultCredentials
                Dim comments As String
                Dim sysArray = CType(Globals.Sheet1.NamedRangeForecastComments.get_Value, System.Array)
                If sysArray(1, 1) Is Nothing OrElse String.IsNullOrEmpty(sysArray(1, 1).ToString) Then
                    comments = String.Empty
                Else
                    comments = sysArray(1, 1).ToString()
                End If

                documentUrl = service.CreateSalesForecastWordDocument(Globals.ThisWorkbook.SalesContactID, _
                        Globals.ThisWorkbook.ForecastID, Globals.ThisWorkbook.ManagerEmployeeID, Globals.ThisWorkbook.TerritoryID, _
                        Globals.ThisWorkbook.ForecastDate, 5, 1, comments, Globals.ThisWorkbook.FullNameURLEncoded)

                If String.IsNullOrEmpty(documentUrl) Then
                    MessageBox.Show("Unable to create your report on the Server.")
                Else
                    ' Open the document for viewing
                    Dim startInfo As ProcessStartInfo = New ProcessStartInfo("winword.exe", """" & documentUrl & """")
                    Process.Start(startInfo)
                End If

            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        Else
            MessageBox.Show("The Workbook needs to be saved to Sales Forecast library before the report can be generated.")
        End If
    End Sub

End Class
